import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { getFileById } from "@/data/file";
import { FileType } from "@/lib/enums";
import { isUrl } from "@/lib/utils";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  if (!id) {
    return NextResponse.json({ error: "Invalid id" }, { status: 403 });
  }
  const file = await getFileById(id);
  if (!file) {
    return NextResponse.json({ error: "Invalid id" }, { status: 403 });
  }

  if (file.type === FileType.Local) {
    const imagePath = path.join(
      process.cwd(),
      process.env.STORAGE_UPLOAD_PATH as string,
      file.data
    );

    // 安全检查：防止目录遍历攻击
    if (!imagePath.startsWith(process.cwd())) {
      return NextResponse.json({ error: "Access denied" }, { status: 403 });
    }

    const imageBuffer = fs.readFileSync(imagePath);
    return new NextResponse(imageBuffer);
  } else {

    if (!isUrl(file.data)) {
      return NextResponse.json({ error: "Missing file URL" }, { status: 403 });
    }

    const remoteResponse = await fetch(file.data);

    if (!remoteResponse.ok) {
      // 如果远程服务器返回错误，将错误状态转发
      return NextResponse.json(
        { error: `Failed to fetch remote file` },
        { status: remoteResponse.status }
      );
    }

    const data = await remoteResponse.arrayBuffer();
    return new NextResponse(data);
  }
}
